package com.tzbank.wisdom.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.tzbank.esb.util.EsbConsumerUtil;
import com.tzbank.utils.CodeUtil;
import com.tzbank.utils.ResultCode;
import com.tzbank.utils.ResultUtil;
import com.tzbank.wisdom.constant.SysConstans;
import com.tzbank.wisdom.service.CreditCardService;
import com.tzbank.wisdom.service.CustomerCenterService;
import com.tzbank.wisdom.service.FinanceService;
import com.tzbank.wisdom.service.LoanService;
import com.tzbank.wisdom.service.SaveService;
import com.tzbank.wisdom.utils.RequestMap;
import com.tzbank.wisdom.utils.ThreadPoolFactory;
import com.tzbank.wisdom.utils.TransCodeEnum;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

@Service
@Slf4j
public class CustomerCenterServiceImpl implements CustomerCenterService {

    //Executors.newFixedThreadPool()

    @Override
    public Map<String, Object> getCustomerMgrInfo(Map<String, String> paramMap) {
        log.info("入参:[{}]", JSONObject.fromObject(paramMap));
        // 组装入参Map
        Map<String, Object> inputMap = new HashMap<String, Object>();
//		Map<String, Object> reqSysHead = new HashMap<String, Object>();
//		//调用核心计价因子报文头入参
//	
//		reqSysHead.put(SysConstans.SYS_TRAN_CODE,  TransCodeEnum.CUSTOMER_MGR_QRY.getServiceCode()); 		// 服务码
//		reqSysHead.put(SysConstans.SYS_TRAN_SENCE, TransCodeEnum.CUSTOMER_MGR_QRY.getServiceSence()); 				// 服务场景
//		reqSysHead.put("targetSysId", "301010");//调用系统代码  核心是301010  信贷是304010
//		reqSysHead.put("consumerId", SysConstans.ABP_CODE);//智脑系统代码
        Map<String, Object> reqSysHead = RequestMap.getReqSysHead(TransCodeEnum.CUSTOMER_MGR_QRY.getServiceCode(), TransCodeEnum.CUSTOMER_MGR_QRY.getServiceSence(), "", SysConstans.ABP_CODE, "301010");

        //调用核心计价因子入参
        inputMap.put("sysHead", reqSysHead);
        inputMap.put("clientNo", paramMap.get("clientNo"));


        Map<String, Object> result = EsbConsumerUtil.clientRequest(inputMap); // 贷记卡自动还款协议签约结果
        log.info("esb 响应[{}]", JSONObject.fromObject(result));
        if (!CodeUtil.CODE_200.getCode().equals(result.get("code"))) {
            return ResultUtil.resultMap(result.get("msg").toString(), ResultCode.RESUTL_CODE_FAILURE.code(),
                    result.get("data"));
        }
        return ResultUtil.resultMap(ResultCode.RESULT_CODE_SUCCESS.desc(), ResultCode.RESULT_CODE_SUCCESS.code(), result.get("data"));
    }




    @Resource
    private LoanService loanService;
    @Resource
    private SaveService saveService;
    @Resource
    private FinanceService financeService;
    @Resource
    private CreditCardService creditCardService;

    @SuppressWarnings({"rawtypes", "unchecked", "unused"})
    public Map<String, Object> getAssetsAndLiabilities(Map reqBody) {

        //最终结果返回结果
        log.info("-------------------进入资产负债方法--------------------");
        long time1 = System.currentTimeMillis();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        /**================================贷款借款===========================================*/
        reqBody.put("clientNo", "1403400002");
        double loanBalance = 0.00;
        //借款总金额通过未还请借据接口查询。累加应还金额
        Map<String, Object> LoanResult = new HashMap<>();
        Future<Map<String, Object>> mapFuture = (Future<Map<String, Object>>) ThreadPoolFactory.getThreadPool().submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return loanService.getLoanDebitMsgQry(reqBody);
            }
        });

        Map<String, Object> SaveResult = new HashMap<>();
        Future<Map<String, Object>> mapFuture1 = (Future<Map<String, Object>>) ThreadPoolFactory.getThreadPool().submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return saveService.getAcctList(reqBody);
            }
        });
        Map<String, Object> Save_DingResult = new HashMap<>();
        Future<Map<String, Object>> mapFuture2 = (Future<Map<String, Object>>) ThreadPoolFactory.getThreadPool().submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return saveService.getFixProductList_Ding(reqBody);
            }
        });
        Map<String, Object> balanceFinanceResult = new HashMap<>();
        Future<Map<String, Object>> mapFuture3 = (Future<Map<String, Object>>) ThreadPoolFactory.getThreadPool().submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return financeService.myProductAll(reqBody);
            }
        });
        try {
            LoanResult = mapFuture.get();
            SaveResult = mapFuture1.get();
            Save_DingResult = mapFuture2.get();
            balanceFinanceResult = mapFuture3.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //  Map<String, Object> LoanResult = loanService.getLoanDebitMsgQry(reqBody);//贷款
        // 当ESB数据返回成功的时候进行数据处理。
        if (CodeUtil.CODE_200.getCode().equals(LoanResult.get("code"))) {
            Map<String, Object> data = (Map<String, Object>) LoanResult.get("data");
            List listArray = (List) data.get("LoanResultArray");
            for (int i = 0; i < listArray.size(); i++) {
                Map<String, Object> kyd = (Map<String, Object>) listArray.get(i);
                loanBalance += (double) kyd.get("retTotalAmt");
            }
            resultMap.putAll(data);
        } else if ("4444".equals(LoanResult.get("code"))) {
            //客户没有未还清的贷款记录
            loanBalance = 0.00;
        }
        long time2 = System.currentTimeMillis();
        long l = time2 - time1;
        log.info("贷款借款所用时间------------------=" + l);
        /**================================活期===========================================*/
        resultMap.put("loanBalance", loanBalance);
        double saveBalance = 0.00;
        //	saveService.getAcctList(reqBody);//活期


        //Map<String, Object> SaveResult = saveService.getAcctList(reqBody);//活期
        // 当ESB数据返回成功的时候进行数据处理。
        if (CodeUtil.CODE_200.getCode().equals(SaveResult.get("code"))) {
            Map<String, Object> data = (Map<String, Object>) SaveResult.get("data");
            List listArray = (List) data.get("listArray");
            for (int i = 0; i < listArray.size(); i++) {
                Map<String, Object> kyd = (Map<String, Object>) listArray.get(i);
                saveBalance += Double.parseDouble((String) kyd.get("balance"));
            }
            data.remove("availablePoint");
            //将
            resultMap.putAll(data);
        } else if ("4444".equals(SaveResult.get("code"))) {
            //客户没有未还清的贷款记录
            saveBalance = 0.00;
        }
        resultMap.put("saveBalance", saveBalance);
        long time3 = System.currentTimeMillis();
        long l1 = time3 - time2;
        log.info("活期所用时间----------------------=" + l1);
        /**================================定期===========================================*/
        double saveDBalance = 0.00;
        //	saveService.getAcctList(reqBody);//活期
        //  Map<String, Object> Save_DingResult = saveService.getFixProductList_Ding(reqBody);//活期
        // 当ESB数据返回成功的时候进行数据处理。
        if (CodeUtil.CODE_200.getCode().equals(Save_DingResult.get("code"))) {
            Map<String, Object> data = (Map<String, Object>) Save_DingResult.get("data");
            List listArray = (List) data.get("SaveDResultArray");
            for (int i = 0; i < listArray.size(); i++) {
                Map<String, Object> kyd = (Map<String, Object>) listArray.get(i);
                saveDBalance += (double) kyd.get("balance");
            }
            data.remove("availablePoint");
            resultMap.putAll(data);
        } else if ("4444".equals(SaveResult.get("code"))) {
            saveDBalance = 0.00;
        }
        resultMap.put("saveDBalance", saveDBalance);
        long time4 = System.currentTimeMillis();
        long l2 = time4 - time3;
        log.info("定期所用时间----------------------=" + l2);
        /**================================理财===========================================*/
        double financebBalance = 0.00;

        //Map<String, Object> balanceFinanceResult = financeService.myProductAll(reqBody);//理财
        // 当ESB数据返回成功的时候进行数据处理。
        if (CodeUtil.CODE_200.getCode().equals(balanceFinanceResult.get("code"))) {
            Map<String, Object> data = (Map<String, Object>) balanceFinanceResult.get("data");
            List listArray = (List) data.get("FinanceResultArray");
            for (int i = 0; i < listArray.size(); i++) {
                Map<String, Object> kyd = (Map<String, Object>) listArray.get(i);
                financebBalance += (double) kyd.get("totPrdValue");
            }
            resultMap.putAll(data);
        } else if ("4444".equals(SaveResult.get("code"))) {
            financebBalance = 0.00;
        }
        resultMap.put("financebBalance", financebBalance);
        long time5 = System.currentTimeMillis();
        long l3 = time5 - time4;
        log.info("理财所用时间----------------------=" + l3);
        /**================================信用卡===========================================*/
        List<String> creditCardList = creditCardService.getCreditCardList(reqBody);
        String creditNo = "";
        for (int i = 0; i < creditCardList.size(); i++) {
            if (i != 0) {
                creditNo = creditNo + "," + creditCardList.get(i);
            } else {
                creditNo = creditCardList.get(i);
            }

        }
        double repayAmtSum = 0.0;
        reqBody.put("creditCardNo", creditNo);
        Map<String, Object> creditCardInfo = new HashMap<>();
        Future<Map<String, Object>> mapFuture4 = (Future<Map<String, Object>>) ThreadPoolFactory.getThreadPool().submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return creditCardService.getCreditCardInfo(reqBody);
            }
        });
        try {
            creditCardInfo = mapFuture4.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //Map<String, Object> creditCardInfo = creditCardService.getCreditCardInfo(reqBody);
        if (CodeUtil.CODE_200.getCode().equals(creditCardInfo.get("code"))) {
            Map<String, List<Map<String, Object>>> dataList = (Map<String, List<Map<String, Object>>>) creditCardInfo.get("data");
            List<Map<String, Object>> data = dataList.get("dataList");
            List<Map<String, Object>> mapList = new ArrayList<>();

            for (int i = 0; i < data.size(); i++) {
                Map<String, Object> resultMap1 = new HashMap<>();
                Map<String, Object> map = data.get(i);
                resultMap1.put("creditCardNo", map.get("creditCardNo"));
                resultMap1.put("repayAmt", map.get("repayAmt"));
                resultMap1.put("curRepayAmt", map.get("curRepayAmt"));
                resultMap1.put("repayAmtMin", map.get("repayAmtMin"));
                resultMap1.put("balance", map.get("balance"));
                //double repayAmt = Double.valueOf(map.get("repayAmt").toString()).doubleValue();
                repayAmtSum += (double) map.get("repayAmt");
                mapList.add(resultMap1);
            }
            resultMap.put("creditCardList", mapList);
            resultMap.put("creditCardRepaySumAmt", repayAmtSum);
        } else if ("4444".equals(SaveResult.get("code"))) {
            repayAmtSum = 0.00;
        }
        long time6 = System.currentTimeMillis();
        long l4 = time6 - time5;
        log.info("信用卡所需时间-------------=" + l4);
        return ResultUtil.resultMap(ResultCode.RESULT_CODE_SUCCESS.desc(), ResultCode.RESULT_CODE_SUCCESS.code(),
                resultMap);
    }
}
